import 'package:flutter/material.dart';
import 'package:flutter_food/core/model/category_model.dart';
import 'package:flutter_food/core/services/local_repository.dart';
import 'package:flutter_food/ui/pages/home/home_category_item.dart';
import 'package:flutter_food/core/ext/int_extension.dart';

// 之前的做法使用StatefulWidget,定于全局变量，请求网络，有刷新的setState比较麻烦
// 此处使用FutureBuilder可以简化该操作
// FutureBuilder适用于刷新频率小的界面，而且界面没有变量。
// 类似上拉加载需要定义page变量就不适用，而我们的首页类目不经常变化就适用
class HomeContentFuture extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<CategoryModel>>(
      builder: (ctx, snapshot) {
        if (!snapshot.hasData) return CircularProgressIndicator();
        var data = snapshot.data;
        return GridView.builder(
            padding: EdgeInsets.all(20.px),
            itemCount: data.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisSpacing: 20.px,
                crossAxisSpacing: 20.px,
                childAspectRatio: 1.5),
            itemBuilder: (ctx, index) {
              return HomeCategoryItem(data[index]);
            });
      },
      future: LocalRepository.getCategoryData(),
    );
  }
}
